<!-- engineering-node.vue -->
<template>
  <view>
    <view style="text-align: right;">
      <wd-button custom-class="custom-btn" @click="handleStageApply" v-if="hasPermission('system:engineering-stage:stage-extension-apply')">申请阶段延期</wd-button>
      <wd-button @click="handleContractApplay" v-if="hasPermission('system:engineering:contract-extension-apply')">申请合同延期</wd-button>
    </view>
	  <wd-collapse v-model="value" class="list">
	    <wd-collapse-item
	      v-for="(firstLevel, index) in engineeringNodeTree"
	      :key="firstLevel.id"
	      :title="firstLevel.stageName"
	      :name="`first${firstLevel.id}`"
        :disabled="calculateDisabled(firstLevel, index)"
	    >
        <template #title="{ expanded, disabled, isFirst }">
          <view class="header">
            <text >{{ firstLevel.stageName }}</text>
            <view>
              <wd-tag type="success" variant="light" use-icon-slot v-if="firstLevel.completeStatus === '1'">
                <template #icon>
                  <wd-icon name="check" size="12px"></wd-icon>
                </template>
                完成
              </wd-tag>
              <wd-tag type="danger" variant="light" use-icon-slot v-if="firstLevel.completeStatus === '0'">
                <template #icon>
                  <wd-icon name="close" size="12px"></wd-icon>
                </template>
                未完成
              </wd-tag>
              <!-- <wd-icon name="chevron-right" size="18px" color="#9fa19f"></wd-icon> -->
            </view>
       
            
          </view>
            <view class="fz-14">
              施工班组：
              <view class="fz-14" @click.stop="handleAssignTeam(firstLevel)">
                <wd-button type="text">{{ firstLevel.teamUserId ? teamUserNames[firstLevel.teamUserId] : '请选择' }}</wd-button>
              </view>
            </view>
            <view class="fz-14">开工日期：
              <view  @click.stop="handleAssignTime(firstLevel)">
                <wd-button type="text">{{ firstLevel.startTime ? dayjs(firstLevel.startTime).format('YYYY-MM-DD') : '请选择' }}</wd-button>
              </view>
            </view>
            <view class="fz-14">完工日期：
              <view  @click.stop="handleAssignTime(firstLevel)">
                <wd-button type="text">{{ firstLevel.endTime ? dayjs(firstLevel.endTime).format('YYYY-MM-DD') : '请选择' }}</wd-button>
              </view>
            </view>
            <view class="fz-14">施工天数：{{ calculateDays(firstLevel.startTime, firstLevel.endTime)
              }}</view>
        </template>
          <!-- 第二层 -->
        	  <wd-collapse v-model="collapseList" class="list">
	            <wd-collapse-item
	              v-for="secondLevel in firstLevel.children"
	              :key="secondLevel.id"
	              :title="secondLevel.stageName"
	              :name="`eng${secondLevel.id}`"
	            >
                <template #title="{ expanded, disabled, isFirst }">
                  <view class="header">
                    <text >{{ secondLevel.stageName }}</text>
                    <wd-tag type="success" variant="light" use-icon-slot v-if="secondLevel.completeStatus === '1'">
                <template #icon>
                  <wd-icon name="check" size="12px"></wd-icon>
                </template>
                完成
              </wd-tag>
              <wd-tag type="danger" variant="light" use-icon-slot v-if="secondLevel.completeStatus === '0'">
                <template #icon>
                  <wd-icon name="close" size="12px"></wd-icon>
                </template>
                未完成
              </wd-tag>
           
           

                  </view>
                  <view>开工日期：{{ secondLevel.startTime ? dayjs(secondLevel.startTime).format('YYYY-MM-DD') : '' }}</view>
                  <view>完工日期： {{ secondLevel.endTime ? dayjs(secondLevel.endTime).format('YYYY-MM-DD') : '' }}</view>
                </template>
                         <!-- 第三层 -->
                     <wd-collapse v-model="third" class="list">
	            <wd-collapse-item
	              v-for="thirdLevel in secondLevel.children"
	              :key="thirdLevel.id"
	              :title="thirdLevel.stageName"
	              :name="`third${thirdLevel.value}`"
                disabled
	            >
                <template #title="{ expanded, disabled, isFirst }">
                  <view class="header">
                    <text style="flex: 1;">{{ thirdLevel.stageName }}</text>
                    <div style="width: 150px;" v-if="thirdLevel.completeStatus === '1'" @click="handleLog(thirdLevel.endTime)">完工日期：{{ thirdLevel.endTime &&
                    dayjs(thirdLevel.endTime).format('YYYY-MM-DD')  }}</div>
                    <wd-button v-if="!thirdLevel.endTime&&hasPermission('system:engineering-stage:confirm-complete')" type="text" @click="handleConfirmComplete(thirdLevel)">确认完成</wd-button>

                  </view>
                </template>

	            </wd-collapse-item>
	              </wd-collapse>

	            </wd-collapse-item>
	          </wd-collapse>
	        </wd-collapse-item>
	      </wd-collapse>

	    <!-- 审批框 -->
    <stick-approve-dialog :order-id="props.orderId" approve-type="23" ref="stickyApproveDialogRef23"/>
    <stick-approve-dialog :order-id="props.orderId" approve-type="24" ref="stickyApproveDialogRef24"/>
  </view>
</template>
<script setup>
import dayjs from 'dayjs';	
import { ref, computed, watch, onMounted, reactive, nextTick } from 'vue';
import { onReady } from '@dcloudio/uni-app';
import {
  useDictionaryStore,
  useUserStore,
  usePermissionStore 
} from '@/store/index.js'
import { getEngineeringStageList,getEngineeringTeamUsers } from '@/api/engineering/detail.js'
import listToTree from '@/utils/listToTree';
import stickApproveDialog from '@/packageA/components/stick-approve-dialog/stick-approve-dialog.vue';
const props = defineProps({
  // 订单id
  engineeringId: {
    type: Number,
    required: true
  },
  companyId: {
    type: Number,
    required: true
  },
  orderId: {
    type: Number,
    required: true,
  },
  contractId: {
    type: Number,
    required: true,
  },
  actualBeginTime: {
    type: String,
    default:'',
  },
  actualEndTime: {
    type: String,
    default:'',
  },
  approveType: {
    type: String,
  }
  
});

// 字典仓库
 const dictionaryStore = useDictionaryStore()
 // 用户仓库
 const userStore = useUserStore()
// 权限参数
const permissionStore = usePermissionStore()
const hasPermission = (permissions) => {
      return permissionStore.hasPermission(permissions)
    }

const value = ref(['first1'])
const collapseList = ref(['eng1'])
const third = ref(['third'])
const handleLog = (e) => {
  console.log(1);
  
  console.log(e,'11');
  
}
// 处理确认完成
const handleConfirmComplete = (row) => {
  const endTime = dayjs(new Date()).format('YYYY-MM-DD 23:59:59');
  if (row.fileUrl) {
      delete row.fileUrl
    }
  uni.navigateTo({
		url: '/packageA/pages/project/engineeringNode/confirmComplete?row='+encodeURIComponent(JSON.stringify({...row,endTime}))
	})

}
// 计算 disabled 状态
const calculateDisabled = (node, index) => {
  node.disabled = false
  // 第一个节点，不禁用
  if (index !== 0) {
    const prevNode = engineeringNodeTree.value[index - 1];
    // 如果 isParallel 为 1，则与上一个节点保持一致
    if (node.isParallel === '1') {
      node.disabled = prevNode.disabled
    } else {
      // 否则，根据上一个节点的完成状态决定
      if (prevNode.completeStatus === '0') {
        node.disabled = true
      }
    }
  }
  return node.disabled;
};
// 施工节点
const engineeringNodeTree = ref([])
// 获取施工节点列表
const handleGetengineeringStageList = () => {
  console.log(111111);
  
  const params = {
    pageSize: -1,
    engineeringId: props.engineeringId
  }
  getEngineeringStageList(params).then(data => {
    engineeringNodeTree.value = listToTree(data.list)
    // 初始化施工班组名称
    initializeTeamUserNames(data.list);
    console.log(engineeringNodeTree.value,'eng');
    
  }).catch((error) => {
    console.log(error);
    	// uni.showToast({
    	// 	title: '获取数据失败',
    	// 	icon: 'error'
    	// })
    })
}
const stickyApproveDialogRef23 = ref(null)
const stickyApproveDialogRef24 = ref(null)
onMounted(async() => {
  handleGetengineeringStageList();
  if (props.approveType === '23')   stickyApproveDialogRef23.value.open();
  if (props.approveType === '24')  stickyApproveDialogRef24.value.open();
  uni.$on('refresh-confirm-complete', handleGetengineeringStageList)
  await nextTick();
});
// 初始化施工班组名称
const initializeTeamUserNames = (list) => {
  list.forEach((item) => {
    if (item.teamUserId) {
      getTeamUserName(item.teamUserId, item.engineeringNode);
    }
  });
};
// 计算施工天数
const calculateDays = (startTime, endTime) => {
  if (!startTime || !endTime) return 0;

  const start = new Date(startTime).getTime();
  const end = new Date(endTime).getTime();

  if (start > end) {
    // console.warn('startTime 不能晚于 endTime');
    return 0;
  }

  const timeDiff = end - start;
  return Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
};
// 施工班组名称映射表
const teamUserNames = ref({});
// 获取施工班组名称
const getTeamUserName = (teamUserId, engineeringNode) => {
  const params = {
    pageSize: -1,
    jobType: engineeringNode,
    companyId: props.companyId,
  };
  getEngineeringTeamUsers(params).then((data) => {
    const teamUserObj = data.list.find((o) => o.id === teamUserId);
    if (teamUserObj) {
      // 将施工班组名称存储到映射表中
      teamUserNames.value[teamUserId] = teamUserObj.name;
    }
  }).catch((error) => {
    console.log(error);
    
    	// uni.showToast({
    	// 	title: '获取数据失败',
    	// 	icon: 'error'
    	// })
    })
};
const handleAssignTeam = (row) => {
  uni.navigateTo({
		url: '/packageA/pages/project/engineeringNode/assignTeam?row='+encodeURIComponent(JSON.stringify({...row,companyId:props.companyId}))
	})
}
const handleAssignTime = (row) => {
   // 全配置
  if(hasPermission('system:engineering-stage:always-config-node-date')) {
    uni.navigateTo({
		  url: '/packageA/pages/project/engineeringNode/assignTime?row='+encodeURIComponent(JSON.stringify({...row}))
	  })
    return
  }
  if(hasPermission('system:engineering-stage:noConfig-config-node-date')) {
    if(row.startTime&&row.endTime)  {  
        return; 
      }
    
  }
  if(!hasPermission('system:engineering-stage:always-config-node-date')&&!hasPermission('system:engineering-stage:noConfig-config-node-date')) {
    return
  }
  uni.navigateTo({
		  url: '/packageA/pages/project/engineeringNode/assignTime?row='+encodeURIComponent(JSON.stringify({...row}))
	  })
}
const handleContractApplay = () => {
  const params = {
    orderId: props.orderId,
    engineeringId: props.engineeringId,
    contractId:props.contractId,
  }
  uni.navigateTo({
		url: '/packageA/pages/project/engineeringNode/contractExtension?row='+encodeURIComponent(JSON.stringify(params))
	})
}
// 计算属性：获取所有顶层未完成节点的扁平化列表
const flatIncompleteNodes = computed(() => {
  return engineeringNodeTree.value
    .filter(node => node.completeStatus === '0')
    .map(node => ({
      id: node.id,
      stageName: node.stageName,
      endTime: node.endTime?dayjs(node.endTime).valueOf():'',
      startTime: node.startTime?dayjs(node.startTime).valueOf():''
    }))
})
const handleStageApply = () => {
  if(flatIncompleteNodes.value.length===0) {
    uni.showToast({
			title: '暂无阶段延期',
			icon: 'none'
		})
    return
  }
  const params = {
    orderId: props.orderId,
    engineeringId: props.engineeringId,
    contractId: props.contractId,
    stageList: flatIncompleteNodes.value,
    actualBeginTime: props.actualBeginTime?dayjs(props.actualBeginTime).valueOf():null,
    actualEndTime: props.actualEndTime?dayjs(props.actualEndTime).valueOf():null,
  }
  console.log(params,111);
  
  uni.navigateTo({
		url: '/packageA/pages/project/engineeringNode/stageExtension?row='+encodeURIComponent(JSON.stringify(params))
	})
}

</script>
<style lang="scss" scoped>
  .custom-layout {
	  height: calc(100vh - 300px);
  }
  .header {
    display: flex;
    justify-content: space-between;
  }
  .fz-14 {
    font-size: 14px;
    color: #9fa19f;
    display: flex;
    align-items: center;
  }
:deep(.custom-btn) {
  margin-right: 4px !important;
}
</style>